package org.liaohailong.helloworld.study;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Author: liaohailong
 * Date: 2021/4/28
 * Time: 20:29
 * Description:
 **/
public class MyCircularQueue {

    private final int[] array;

    private int head;
    private int tail;
    private int size;

    public MyCircularQueue(int k) {
        array = new int[k];
        head = -1;
        tail = -1;
        size = 0;
    }

    public boolean enQueue(int value) {
        if (isFull()) return false;
        size++;
        tail = (tail + 1) % array.length;
        array[tail] = value;
        // 第一次添加
        if (head <= -1) head = 0;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) return false;
        size--;
        array[head] = -1;
        head = (head + 1) % array.length;
        return true;
    }

    public int Front() {
        if (isEmpty()) return -1;
        return array[head];
    }

    public int Rear() {
        if (isEmpty()) return -1;
        return array[tail];
    }

    public boolean isEmpty() {
        return size <= 0;
    }

    public boolean isFull() {
        return size >= array.length;
    }

    public static void main(String[] args) {
        // 1. Initialize a queue.
        Queue<Integer> q = new LinkedList<>();
        // 2. Get the first element - return null if queue is empty.
        System.out.println("The first element is: " + q.peek());
        // 3. Push new element.
        q.offer(5);
        q.offer(13);
        q.offer(8);
        q.offer(6);
        // 4. Pop an element.
        q.poll();
        // 5. Get the first element.
        System.out.println("The first element is: " + q.peek());
        // 7. Get the size of the queue.
        System.out.println("The size is: " + q.size());
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */
